<?php

/**
 * Object representation of a Token table in the database.
 */
class TokenTable {
	/**
	 * Gets a token object from the database by looking for it's string representation.
	 * 
	 * @param	tokenString	String rperesentation of the token to get.
	 * @return The corresponding Token object or NULL if none was found.
	 */
	public static function getByString($tokenString) {
		// Check input:
		if (!$tokenString) {
			return NULL;
		}
		
		// Fetch DB connection:
		$db = Database::getDB();
		
		// Prepare a statement:
		$stmt = $db->prepare("SELECT * FROM Tokens WHERE tokenString = :tokenString LIMIT 1");
		$stmt->bindParam(":tokenString", $tokenString);
		
		// Fetch result:
		Logger::log("TokenTable", "Fetching token from DB.");
		$stmt->execute();
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		Logger::log("TokenTable", "Token fetched.");
		
		// Make and return object:
		$tokenFactory = new TokenFactory();
		return $tokenFactory->fromRow($row);
	}
	
	
	
	/**
	 * Gets a token by looking for the given user/ip combination.
	 * 
	 * @param userID 	ID of the user.
	 * @param ipAddress	IP Address of the user.
	 * @return The token object corresponding to the user/ip or NULL if not found.
	 */
	public static function get($userID, $ipAddress) {
		// Check input:
		if (!$userID or !$ipAddress) {
			return NULL;
		}
		
		// Get DB connection:
		$db = Database::getDB();
		
		// Prepare statement:
		$stmt = $db->prepare("SELECT * FROM Tokens WHERE ipAddress = :ipAddress AND userID = :userID LIMIT 1");
		$stmt->bindValue(":ipAddress", ip2long($ipAddress));
		$stmt->bindValue(":userID", $userID);
		
		// Execute:
		Logger::log("TokenTable", "Fetching token for user/ip.");
		$stmt->execute();
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		Logger::log("TokenTable", "Token fetched.");
		
		// Transform to object and return;
		$tokenFactory = new TokenFactory();
		return $tokenFactory->fromRow($row);
	}
	
	
	
	/**
	 * Inserts a new token in the database.
	 * 
	 * @param token	The token to insert.
	 */
	public static function insert(Token $token) {
		// Check input:
		if (!$token or !$token->getUser()) {
			return;
		}
		
		// Get DB connection:
		$db = Database::getDB();
		
		// Prepare statement:
  		$stmt = $db->prepare("INSERT INTO Tokens (tokenString, userID, ipAddress, firstLogin, lastLogin) VALUES (:tokenString, :userID, :ipAddress, :firstLogin, :lastLogin)");
  		$stmt->bindValue(":tokenString", $token->getTokenString());
  		$stmt->bindValue(":userID", $token->getUser()->getID());
  		$stmt->bindValue(":ipAddress", $token->getIPAddress());
  		$stmt->bindValue(":firstLogin", $token->getFirstLogin());
  		$stmt->bindValue(":lastLogin", $token->getLastLogin());
		
  		// Execute query:
  		Logger::log("TokenTable", "Inserting a new token into the DB.");
  		$stmt->execute();
  		Logger::log("TokenTable", "Token inserted.");
	}
}